<?php

namespace app\admin\model;

use app\model\Model;

class Member extends Model
{
  public $privilege = 'member';
  public $cids;
  public $id;
  public $page;
  public $db;

  function __construct()
  {
    include 'check.php';
    new Check();

    $this->db = $GLOBALS['db'];
    $this->cids = checkAdminPriv(@$this->privilege); // 判断权限
    $this->id = intval($_GET['id']);
    $this->page = max(intval($_GEt['page'] . 1));
  }

  function index()
  {
    include_once LIB_PATH . 'cls.page.php';

    $pager = new \Page(ADMIN_PAGE_SIZE);

    // search
    $keyword = str_safe($_GET['keyword']);
    $where = "1 ";

    if (!is_null($keyword) && '' != $keyword) {
      // mobile is int
      $where .= intval($keyword) ? "AND INSTR(u_mobile, $keyword) " : "AND INSTR(u_name, '$keyword') ";
    }

    $pager->handle($GLOBALS['db']->getOne("SELECT COUNT(*) FROM user WHERE $where"));

    $this->tpl('member', [
      'db' => $this->db,
      'list' => $GLOBALS['db']->getAll("SELECT * FROM user WHERE $where ORDER BY id DESC LIMIT " . $pager->page_start . "," . $pager->page_size),
      'pager' => $pager,
    ]);
  }

  function view()
  {
    $this->tpl('member_view', [
      'row' => $GLOBALS['db']->getRow("SELECT * FROM user WHERE id = $this->id"),
    ]);
  }

  function batch()
  {
    null_back($_POST['id'], '请至少选中一项！');
    $id = array_str($_POST['id']);

    switch ($_POST['execute_method']) {
      case 'enable':
        $sql = "UPDATE user SET u_enable = 1 WHERE id in ($id)";
        break;
      case 'unable':
        $sql = "UPDATE user SET u_enable = 0 WHERE id in ($id)";
        break;
      default:
        alert_back('请选择要执行的操作');
    }

    if ($GLOBALS['db']->exec($sql)) {
      switch ($_POST['execute_method']) {
        case 'enable':
          admin_log("用户生效 [$id]");
          break;
        case 'unable':
          admin_log("用户失效 [$id]");
          break;
      }

      alert_href($GLOBALS['lang']['msg_success'], M('admin', 'member') . "&page = $this->page");
    }

    alert_back($GLOBALS['lang']['msg_tryagain']);
  }

  function del()
  {
    if ($GLOBALS['db']->exec("DELETE FROM user WHERE id = $this->id")) {
      admin_log("会员删除 [$this->id]");
      alert_href($GLOBALS['lang']['msg_success'], M('admin', 'member') . "&page = $this->page");
    }

    alert_back($GLOBALS['lang']['msg_tryagain']);
  }

  function __destruct()
  {
  }
}